﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using SubsDownloader.Core.Entities;
using SubsDownloader.Core.EventArgs;

namespace SubsDownloader.Core.Providers
{
    public class SratimProvider : SubtitlesProvider
    {
        private const string SearchURL = "Http://www.sratim.co.il/browse.php?q=";
        private const string MoviePageURL = "http://www.sratim.co.il/view.php?id=";
        private const string SubtitlesPageURL = "http://www.sratim.co.il/subtitles.php?mid=";
        private const int Timeout = 200000;

        public override string Name
        {
            get { return "Sratim"; }
        }

        protected override TitleResult[] FindTitles ( TitleFileInfo titleFileInfo )
        {
            HttpWebRequest request;
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create( SearchURL + titleFileInfo.TitleName );
                request.Timeout = Timeout;
                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader( response.GetResponseStream() );
                string html = reader.ReadToEnd();

                TitleResult[] results = AnalyzeMovieResults( html, titleFileInfo );

                return results;
            }
            catch (TimeoutException)
            {
                InvokeProgressChanged( new SubsProgressEventArgs( titleFileInfo, 0, "GetTitles Timeout" ) );
                return null;
            }
            catch (Exception e)
            {
                InvokeProgressChanged( new SubsProgressEventArgs( titleFileInfo, 0, e.Message ) );
                return null;
            }
            finally
            {
                if (response != null)
                    response.Close();
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }
        }

        protected override SubtitleResult[] FindSubtitles ( TitleFileInfo titleFileInfo, TitleResult movieResult )
        {
            Match match = null;
            SubtitleResult[] list;
            StreamReader reader = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            List<SubtitleResult> list2 = null;
            Match match2 = null;
            try
            {
                string html = null;
                if (titleFileInfo.IsSeries)
                {
                    request = (HttpWebRequest)WebRequest.Create( movieResult.Url );
                    request.Timeout = 0x9c40;
                    request.Proxy = null;
                    request.AllowAutoRedirect = false;
                    response = (HttpWebResponse)request.GetResponse();
                    reader = new StreamReader( response.GetResponseStream() );
                    match2 = Regex.Match( reader.ReadToEnd(), @"(?<=seasonlink_)\d+(?=[^>]+>" + Convert.ToInt32( titleFileInfo.Season ) + "<)" );
                    request = (HttpWebRequest)WebRequest.Create( movieResult.Url + "&s=" + match2.Value );
                    request.Timeout = 0x9c40;
                    request.Proxy = null;
                    response = (HttpWebResponse)request.GetResponse();
                    reader = new StreamReader( response.GetResponseStream() );
                    match = Regex.Match( reader.ReadToEnd(), @"(?<=episodelink_)\d+(?=[^>]+>" + Convert.ToInt32( titleFileInfo.Episode ) + "<)" );
                    request = (HttpWebRequest)WebRequest.Create( movieResult.Url + "&s=" + match2.Value + "&e=" + match.Value );
                    request.Timeout = 0x9c40;
                    request.Proxy = null;
                    response = (HttpWebResponse)request.GetResponse();
                    reader = new StreamReader( response.GetResponseStream() );
                    html = reader.ReadToEnd();
                }
                else
                {
                    request = (HttpWebRequest)WebRequest.Create( movieResult.Url );
                    request.Timeout = 0x9c40;
                    request.Proxy = null;
                    response = (HttpWebResponse)request.GetResponse();
                    reader = new StreamReader( response.GetResponseStream() );
                    html = reader.ReadToEnd();
                }
                list = AnalyzeSubtitleResults( html, titleFileInfo );

            }
            catch (TimeoutException)
            {
                InvokeProgressChanged( new SubsProgressEventArgs( titleFileInfo, 0, "GetSubtitles Timeout" ) );
                return null;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                response.Close();
                reader.Close();
                reader.Dispose();
            }
            return list;
        }

        #region Private Methods

        private TitleResult[] AnalyzeMovieResults ( string html, TitleFileInfo title )
        {
            Match titleId = null;
            Match isSeries = null;
            Match match3 = null;
            Match titleName = null;
            Match year = null;

            var list = new List<TitleResult>();
            for (match3 = Regex.Match( html, "<div style=\"width:216px;padding-right:10px;padding-left:14px;.*?</td>", RegexOptions.Singleline ); match3.Success; match3 = match3.NextMatch())
            {
                TitleResult item = new TitleResult( title );
                isSeries = Regex.Match( match3.Value, "סדרה", RegexOptions.Singleline );

                string regexName = "class=\"smtext\">(?<movieName>.*?)</div>";
                titleName = Regex.Match( match3.Value, regexName, RegexOptions.Singleline );

                if (!titleName.Success)
                {
                    regexName = "class=\"subtext\">(?<movieName>.*?)</a>";
                    titleName = Regex.Match( match3.Value, regexName, RegexOptions.Singleline );
                }
                titleId = Regex.Match( match3.Value, @"(?<=id=)\d+", RegexOptions.Singleline );


                if (!isSeries.Success)
                {
                    year = Regex.Match( match3.Value, "(?<=<span class=\"smtext\">)\\d\\d\\d\\d(?=</span>)", RegexOptions.Singleline );
                    item.Year = year.Value.Trim();
                }

                item.Name = titleName.Groups["movieName"].Value.Trim();
                item.IsSeries = isSeries.Success;

                if (item.IsSeries)
                {
                    item.Url = "http://www.sratim.co.il/viewseries.php?id=" + titleId.Value.Trim();
                }
                else
                {
                    item.Url = "http://www.sratim.co.il/view.php?m=subtitles&id=" + titleId.Value.Trim();
                }
                list.Add( item );
            }
            return list.ToArray();
        }


        private SubtitleResult[] AnalyzeSubtitleResults ( string html, TitleFileInfo title )
        {
            var subtitleResults = new List<SubtitleResult>();
            var subtitleResult = Regex.Match( html, "subtitle_tab.+?</table>", RegexOptions.Singleline );

            while (subtitleResult.Success)
            {
                var name = Regex.Match( subtitleResult.Value, "(?<=subtitle_title.+?title=.).+?(?=\")" );
                var language = Regex.Match( subtitleResult.Value, "images/Flags/1.png" );
                var cdCount = Regex.Match( subtitleResult.Value, "(?<=images/cds/cd)\\d" );
                var link = Regex.Match( subtitleResult.Value, "downloadsubtitle.php\\?id=\\d+" );

                if (language.Success)
                {
                    var subResult = new SubtitleResult( title );
                    subResult.Name = name.Value.Trim();
                    subResult.CDCount = cdCount.Value.Trim();
                    subResult.Link = "Http://www.sratim.co.il/" + link.Value.Trim();
                    subtitleResults.Add( subResult );

                }
                subtitleResult = subtitleResult.NextMatch();
            }

            return subtitleResults.ToArray();
        }

        #endregion
    }
}
